package xin.jpetstore.httpclient;

import java.io.File;
import java.net.URI;

import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class DoGETParam {

    public static void main(String[] args) throws Exception {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

//        String url = "http://www.oschina.net/search?scope=project&q=java";
        // 定义请求的参数
         URI uri = new URIBuilder("http://www.oschina.net/search").setParameter("q", "java").build();

        System.out.println(uri.toString());

        // 创建http GET请求
         HttpGet httpGet = new HttpGet(uri);
//        HttpGet httpGet = new HttpGet(url);
        
        //模拟浏览器访问，加入浏览器的信息到header
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36");

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                FileUtils.writeStringToFile(new File("d:/0707/baidu.html"), content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }

}
